﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XmlToJson;

namespace kvv_forms
{
    class ConvertorModel
    {
        public string GetData(string XMLData, bool AttribRead, bool CommentRead, bool CDataRead, bool TextNodeRead, bool MarkingUsing)
        {
            Сonfig CurrConfig = new Сonfig();
            CurrConfig.readAttrib = AttribRead;
            CurrConfig.readCdata = CDataRead;
            CurrConfig.readComment = CommentRead;
            CurrConfig.readTextNode = TextNodeRead;
            ConvertorFactory ConFactory = new ConvertorFactory();
            Convertor CurrConvertor = ConFactory.BuildConvertor(CurrConfig);
            if(MarkingUsing)
            return Marking(CurrConvertor.ConvertXML(XMLData));
            else return CurrConvertor.ConvertXML(XMLData);
        }
        private string Marking(string JsonData)
        {   
            string MarkedJsonData = "";
            int TabIndex = 0, i, j = 0;
            for (i = 0; i < JsonData.Length; i++)
                switch (JsonData[i])
                {
                    case '{':
                        {   
                            if(i!=0)
                            MarkedJsonData += "\r\n";
                            for (j = 0; j < TabIndex; j++)
                                MarkedJsonData += "    ";
                            MarkedJsonData += JsonData[i] + "\r\n";
                            TabIndex++;
                            for (j = 0; j < TabIndex; j++)
                                MarkedJsonData += "    ";
                            break;
                        }
                    case '}':
                        {
                            MarkedJsonData += "\r\n";
                            TabIndex--;
                            for (j = 0; j < TabIndex; j++)
                                MarkedJsonData += "    ";
                            MarkedJsonData += JsonData[i];
                            break;
                        }
                    case ',':
                        {
                            if (JsonData[i - 1] == '"' || JsonData[i - 1] == '}' || JsonData[i - 1] == '/')
                            {
                                MarkedJsonData += JsonData[i] + "\r\n";
                                for (j = 0; j < TabIndex; j++)
                                    MarkedJsonData += "    ";
                            }
                            else
                                MarkedJsonData += JsonData[i];
                            break;
                        }
                    default:
                        {
                            MarkedJsonData += JsonData[i];
                            break;
                        }
                }
            return MarkedJsonData;
        }
    }
}
